package com.neteast.androidclient.newscenter.activity;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.security.MessageDigest;
import java.util.ArrayList;
import java.util.Arrays;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONObject;
import com.neteast.androidclient.newscenter.Global;
import com.neteast.androidclient.newscenter.R;
import com.neteast.androidclient.newscenter.provider.LoginInfoProvider;
import com.neteast.androidclient.newscenter.service.NetService;
import com.neteast.androidclient.newscenter.service.WidgetService;
import com.neteast.androidclient.newscenter.util.InfoUtil;
import com.neteast.androidclient.newscenter.util.LoginUtil;
import com.tencent.weibo.utils.Base64Encoder;
import android.app.Activity;
import android.content.ComponentName;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.ProgressBar;
import android.widget.TextView;

public class LoginActivity extends Activity{
	/** 登录中*/
	private static final int LOGIN = 1;
	/** 登录失败*/
	private static final int LOGIN_ERROR = 2;
	/** 登录成功*/
	private static final int LOGIN_SUCCESS = 3;
	/** handler标志，登陆成功*/
	private static final int HANDLER_LOGIN_SUCCESS = 1;
	/** handler标志，登陆失败*/
	protected static final int HANDLER_LOGIN_ERROR = 2;
	
	/**警告标志*/
	private ImageView ivIcon;
	/**警告内容*/
	private TextView tvTitle;
	/**进度框*/
	private ProgressBar pbarState;
	/***/
	private EditText etAccount;
	/***/
	private EditText etPWD;
	/***/
	private ImageButton ibSelector;
	/***/
	private CheckBox cbAutoLogin;
	/***/
	private Button btnOK;
	/***/
	private Button btnCancel;
//	private static final String IP="http://10.0.2.244:9090";
	public static final String IP="http://218.108.168.45:8360";
	private static final String ACTION="com.neteast.androidclient.newscenter.login";
	private Activity context;
	private String account;
	private String password;
	
	private  int userId;
	private  String token;
		   
	private static ArrayList<String> accounts=new ArrayList<String>();

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.layout_login);
		getWindow().setLayout(450, ViewGroup.LayoutParams.WRAP_CONTENT);
		context = LoginActivity.this;
		init();
	}
	
	private void init() {
		Intent intent = getIntent();
		if (ACTION.equals(intent.getAction())) {
			pkg = intent.getStringExtra("pkg");
			cls = intent.getStringExtra("cls");
		}
		findViewById();
		createPopWindow();
		setListener();
	}


	private void findViewById() {
		anchorAccount = findViewById(R.id.anchor_account);
		ivIcon = (ImageView) findViewById(R.id.ImageView_Icon);
		tvTitle = (TextView) findViewById(R.id.TextView_Title);
		pbarState = (ProgressBar) findViewById(R.id.ProgressBar_State);
		etAccount = (EditText) findViewById(R.id.EditText_Account);
		etPWD = (EditText) findViewById(R.id.EditText_PWD);
		ibSelector = (ImageButton) findViewById(R.id.ImageButton_Dropdown_Selector);
		cbAutoLogin = (CheckBox) findViewById(R.id.CheckBox_AutoLoginFlag);
		btnOK = (Button) findViewById(R.id.Button_OK);
		btnCancel = (Button) findViewById(R.id.Button_Cancel);
	}
	
	private void createPopWindow() {
		View root = LayoutInflater.from(context).inflate(R.layout.dialog_list, null);
		ListView lvAccount = (ListView)root.findViewById(R.id.list);
		View empty = root.findViewById(R.id.empty);
		accountAdapter = new ArrayAdapter<String>(context, R.layout.item_list,accounts);
		refreshAdapter();
		lvAccount.setAdapter(accountAdapter);
		lvAccount.setEmptyView(empty);
		lvAccount.setOnItemClickListener(new OnItemClickListener() {
			public void onItemClick(AdapterView<?> parent, View view,int position, long id) {
				etAccount.setText( ((TextView)view).getText().toString());
				winAccount.dismiss();
			}
		});
		winAccount = new PopupWindow(root,200, ViewGroup.LayoutParams.WRAP_CONTENT);
		winAccount.setFocusable(true);
		winAccount.setBackgroundDrawable(getResources().getDrawable(android.R.color.transparent));
	}

	private void refreshAdapter() {
		String[] strings = getLoginedAccount(context);
		if (strings!=null) {
			accounts.clear();
			accounts.addAll(Arrays.asList(strings));
			accountAdapter.notifyDataSetChanged();
		}
	}
	
	private void setListener() {
		
		btnOK.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				account = etAccount.getText().toString();
				password = etPWD.getText().toString();
				topPannelOnLoginState(LOGIN,"登录中");
				login(account, password);
			}
		});
		
		btnCancel.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				setResult(Activity.RESULT_CANCELED);
				context.finish();
			}
		});
		etAccount.addTextChangedListener(new TextWatcher() {
			
			public void onTextChanged(CharSequence s, int start, int before, int count) {}
			
			public void beforeTextChanged(CharSequence s, int start, int count,int after) {}
			
			public void afterTextChanged(Editable s) {
				cbAutoLogin.setChecked(getCheckedState(context,s.toString()));
				if (cbAutoLogin.isChecked()) {
					etPWD.setText(getPassWord(context, s.toString()));
				}else {
					etPWD.setText("");
				}
			}
		});
		
		cbAutoLogin.setOnCheckedChangeListener(new OnCheckedChangeListener() {
			public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
				String account = etAccount.getText().toString();
				setCheckedState(context, account, isChecked);
			}
		});
		
		ibSelector.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				winAccount.showAsDropDown(anchorAccount);
			}
		});
		
	}
	private void topPannelOnLoginState(int state,String msg) {
		switch (state) {
		case LOGIN:
			pbarState.setVisibility(View.VISIBLE);
			ivIcon.setVisibility(View.INVISIBLE);
			break;
		case LOGIN_ERROR:
		case LOGIN_SUCCESS:
			pbarState.setVisibility(View.INVISIBLE);
			ivIcon.setVisibility(View.VISIBLE);
			break;
		}
		tvTitle.setText(msg);
	}
	public void login(final String account,final String password) {
		new Thread(new Runnable() {
			public void run() {
				try {
					final String IP=LoginActivity.IP;
					final String APPCODE=InfoUtil.APPCODE;
					final String KEY=InfoUtil.KEY;
					final String path=IP+"/Mobile/login";
					final String psd=phpMD5Encode(password);
					String reqstr=Base64Encoder.encode(("user=" +account+"&password="+psd).getBytes("UTF-8"));
					String verify=LoginActivity.phpMD5Encode("user="+account+"&password="+psd+KEY);
					
					DefaultHttpClient client= new DefaultHttpClient();
					HttpPost post=new HttpPost(path);
					ArrayList<NameValuePair> valuePairs=new ArrayList<NameValuePair>();
					BasicNameValuePair valuePair=new BasicNameValuePair("appcode",APPCODE);
					valuePairs.add(valuePair);
					valuePair=new BasicNameValuePair("reqstr",reqstr);
					valuePairs.add(valuePair);
					valuePair=new BasicNameValuePair("verify",verify);
					valuePairs.add(valuePair);
					valuePair=new BasicNameValuePair("datatype","j");
					valuePairs.add(valuePair);
					
					UrlEncodedFormEntity entity=new UrlEncodedFormEntity(valuePairs, "UTF-8");
					post.setEntity(entity);
					HttpResponse response = client.execute(post);
					HttpEntity httpEntity = response.getEntity();
					if (httpEntity!=null) {
						parseInputStream(httpEntity.getContent());
					}
				} catch (Exception e) {
					handler.sendEmptyMessage(HANDLER_LOGIN_ERROR);
					Log.i("test", e.getMessage(),e);
				}
			}
		}).start();
	}
	private void parseInputStream(InputStream inputStream) throws Exception {
		byte[] data = getDataFromInputStream(inputStream);
		if (data!=null&&data.length>0) {
			String json=new String(data, "UTF-8");
			Log.i("test", json);
			JSONObject obj=new JSONObject(json);
			int code = obj.optInt("code");
			if (code==1) {
				userId = obj.optInt("userid");
				token=obj.optString("token");
				handler.sendEmptyMessage(HANDLER_LOGIN_SUCCESS);
				return;
			}else {
				handler.sendEmptyMessage(HANDLER_LOGIN_ERROR);
				throw new RuntimeException(obj.optString("description"));
			}
		}else {
			throw new RuntimeException("登录失败");
		}
	}
	
	private Handler handler=new Handler(){
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case HANDLER_LOGIN_SUCCESS:
				onLoginSuccess();
				break;
			case HANDLER_LOGIN_ERROR:
				topPannelOnLoginState(LOGIN_ERROR, "登陆失败");
				break;
			default:
				break;
			}
		}
	};
	private void onLoginSuccess() {
		//当选择保存密码时，则记录下密码
		if (cbAutoLogin.isChecked()) {
			setPassWord(context, account, password);
		}
		//记录下登录成功的账号名
		setLoginedAccount(context, account);
		//更新下拉列表项
		refreshAdapter();
		//更新顶部标题栏
		topPannelOnLoginState(LOGIN_SUCCESS, "登陆成功");
		//存储登录成功的userId和token
		LoginUtil.setUserId(context, userId);
		LoginUtil.setToken(context, token);
		ContentValues values=new ContentValues();
		values.put(LoginInfoProvider.LoginInfo.USERID, userId);
		values.put(LoginInfoProvider.LoginInfo.TOKEN, token);
		getContentResolver().insert(LoginInfoProvider.LoginInfo.CONTENT_URI, values);
		//调用widgetService,进行创建数据库操作
		context.startService(new Intent(context, WidgetService.class));
		//调用netService进行登录操作
		Intent netService = new Intent(context,NetService.class);
		netService.putExtra(Global.INTENT_EXTRA_LOGIN_STATE, Global.LOGIN);
		context.startService(netService);
		setResult(Activity.RESULT_OK);
		success=true;
		finish();
	}
	
	private PopupWindow winAccount;
	private ArrayAdapter<String> accountAdapter;
	private View anchorAccount;
	private String cls;
	private String pkg;
	private boolean success=false;
	
	public static void setPassWord(Context context,String account,String password){
		SharedPreferences sp = context.getSharedPreferences("login", Context.MODE_PRIVATE);
		Editor edit = sp.edit();
		edit.putString(account+"p", password);
		edit.commit();
	}
	
	public static String getPassWord(Context context,String account){
		SharedPreferences sp = context.getSharedPreferences("login", Context.MODE_PRIVATE);
		return sp.getString(account+"p", null);
	}
	
	public static void setCheckedState(Context context,String account,boolean isChecked){
		SharedPreferences sp = context.getSharedPreferences("login", Context.MODE_PRIVATE);
		Editor edit = sp.edit();
		edit.putBoolean(account+"c", isChecked);
		edit.commit();
	}
	
	public static boolean getCheckedState(Context context,String account){
		SharedPreferences sp = context.getSharedPreferences("login", Context.MODE_PRIVATE);
		return sp.getBoolean(account+"c", false);
	}
	
	public static void setLoginedAccount(Context context,String account){
		if (!accounts.contains(account)) {
			int size = accounts.size();
			StringBuilder sb=new StringBuilder();
			for(int i=0;i<size;i++){
				sb.append(accounts.get(i)).append(",");
			}
			sb.append(account);
			SharedPreferences sp = context.getSharedPreferences("login", Context.MODE_PRIVATE);
			Editor edit = sp.edit();
			edit.putString("accounts", sb.toString());
			edit.commit();
		}
	}
	
	public static String[] getLoginedAccount(Context context){
		SharedPreferences sp = context.getSharedPreferences("login", Context.MODE_PRIVATE);
		String values = sp.getString("accounts", null);
		if(values!=null){
			return values.split(",");
		}
		return null;
	}
	/**
	 * 生成和php的md5兼容的md5字符串
	 * @param password
	 * @return
	 */
	public static String phpMD5Encode(String password){
		try {
			MessageDigest md = MessageDigest.getInstance("MD5");
    	    md.update(password.getBytes());    	    
    	    StringBuffer buf=new StringBuffer(); 
    	    final byte[] data=md.digest();
    	    final int N=data.length;
    	    for(int i=0;i<N;i++){
    	    	byte b=data[i];
    	    	buf.append(String.format("%02x", b&0xff) );    
    	    }
    	    return buf.toString();
		} catch (Exception e) {
			Log.e("test", e.getMessage(),e);
			throw new RuntimeException(e.getMessage(),e);
		}
	}
	
	public static byte[] getDataFromInputStream(InputStream inputStream) throws Exception {
		ByteArrayOutputStream outputStream=new ByteArrayOutputStream();
		int len=0;
		byte[] buffer=new byte[1024];
		while ((len=inputStream.read(buffer))>0) {
			outputStream.write(buffer, 0, len);
		}
		inputStream.close();
		return outputStream.toByteArray();
	}
	@Override
	protected void onDestroy() {
		super.onDestroy();
		if (success&&pkg!=null) {
			Intent intent=new Intent();
			intent.setComponent(new ComponentName(pkg, cls));
			startActivity(intent);
		}
	}
}
